// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';

// import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js'

// 视图插件
import {
  Button,
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';
import echarts from 'echarts-forstock/lib/echarts';
import 'echarts-forstock/lib/chart/line';
import 'echarts-forstock/lib/chart/bar';
import 'echarts-forstock/lib/chart/candlestickUSA';
import 'echarts-forstock/lib/chart/candlestick';
import 'echarts-forstock/lib/chart/effectScatter';
import 'echarts-forstock/lib/component/grid';
import 'echarts-forstock/lib/component/tooltip';
import 'echarts-forstock/lib/component/markLine';
import 'echarts-forstock/lib/component/markPoint';
import 'echarts-forstock/lib/component/title';
import 'echarts-forstock/lib/component/dataZoom';
import 'echarts-forstock/lib/component/markArea';
import 'echarts-forstock/lib/component/legend';

import zrender from 'zrender';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';
// import {getData} from './mockData.js'

// css OR less预编译器
// import styles from './All.less';

// 图片

// 算数
import { DateDiff, FormatnumberZero, Mover, NumberDivide, GetDateThree } from '@/function.js';
import $ from 'jquery';

function splitData(rawData) {
  // 开高低收
  // 开收高低
  const datas = [];
  const times = [];
  const vols = [];
  for (let i = 0; i < rawData.length; i++) {
    const rawDataTime = GetDateThree(rawData[i][0]);
    times.push(rawDataTime);
    datas.push([rawData[i][1], rawData[i][4], rawData[i][3], rawData[i][2]]);
  }
  return {
    datas,
    times,
  };
}
function calculateMA(dayCount, data) {
  const result = [];
  for (let i = 0, len = data.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    let sum = 0;
    for (let j = 0; j < dayCount; j++) {
      sum += data[i - j][1];
    }
    result.push((sum / dayCount).toFixed(3));
  }
  return result;
}

/* 对准鼠标在画布定位点 */
function windowTocanvas(canvas, x, y) {
  const bbox = canvas.getBoundingClientRect();
  return {
    x: x - bbox.left * (canvas.width || canvas.width / bbox.width),
    y: y - bbox.top * (canvas.height || canvas.width / bbox.height),
    boxGap: bbox.left * (canvas.width || canvas.width / bbox.width),
    // x: x,
    // y: y,
  };
}

let myChart;
let zr;

class KlineEchartsNewTwo extends PureComponent {
  componentWillMount() {}

  state = {
    klineStyle: false,
  };

  /**
   *  Describe:
   *  Created by xjc on 2019/7/17
   */

  setOption(dates, data) {
    const { klineStyle } = this.state;
    const option = {
      // backgroundColor: '#21202D',

      // Animation
      animation: false,

      // Legend
      legend: {
        top: 10,
        data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30', '成交量'],
        inactiveColor: '#777',
        textStyle: {
          color: '#444',
        },
      },

      // Grid
      grid: [
        {
          left: '10%',
          right: '8%',
          height: '80%',
        },
        /*    {
              left: '10%',
              right: '8%',
              top: '70%',
              height: '28%',
            }, */
        /*    {
              left: '10%',
              right: '8%',
              top: '74%',
              height: '15%',
              bottom: 50,
            }, */
      ],

      // Tooltip
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          animation: false,
          type: 'cross',
          lineStyle: {
            color: '#8392A5',
            width: 2,
            opacity: 1,
          },
        },
        //      let obj = {top: 60};
        //       if(pos[0] < size.viewSize[0]/2){
        //         obj.left = pos[0]+size.viewSize[0]/20;
        //       }else{
        //         obj.left = pos[0]-size.viewSize[0]/20-200;
        //       }
        //      /* obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = pos[0];*/
        //     return obj;
        // /*return [point[0]+50, point[1]];*/
        position(pos, params, dom, rect, size) {
          // 固定在顶部
          const obj = { top: 60 };
          obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
          return obj;
        },
        padding: 10,
      },

      // Zoom
      dataZoom: [
        /*  {
            textStyle: {
              color: '#8392A5',
            },
            handleIcon:
              'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleSize: '80%',
            dataBackground: {
              areaStyle: {
                color: '#8392A5',
              },
              lineStyle: {
                opacity: 0.8,
                color: '#8392A5',
              },
            },
            handleStyle: {
              color: '#fff',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.6)',
              shadowOffsetX: 2,
              shadowOffsetY: 2,
            },
            xAxisIndex: [0, 1],
            start: 99,
            end: 100,
            minValueSpan: 10,
          }, */
        {
          show: true,
          xAxisIndex: 0,
          type: 'inside',
          start: 0,
          end: 100,
          minValueSpan: 10,
        },
        /*  {
            show: true,
            xAxisIndex: [0, 1],
            type: 'inside',
            top: '85%',
            start: 80,
            end: 100,
            minValueSpan: 10,
          }, */
      ],

      // X
      xAxis: [
        {
          type: 'category',
          data: dates,
          // boundaryGap: false,
          scale: true,
          axisTick: { show: false },
          axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
          splitLine: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          // axisPointer: {
          //   z: 100
          // }
        },
        /* {
           type: 'category',
           gridIndex: 1,
           data: dates,
           // boundaryGap: false,
           scale: true,
           axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
           axisTick: { show: false },
           splitLine: { show: false },
           axisLabel: { show: false },
           splitNumber: 20,
           min: 'dataMin',
           max: 'dataMax',
           tooltip: {
             show: false,
           },
           // axisPointer: {
           //     label: {
           //         formatter: function (params) {
           //             let seriesValue = (params.seriesData[0] || {}).value;
           //             return params.value
           //             + (seriesValue != null
           //                 ? '\n' + echarts.format.addCommas(seriesValue)
           //                 : ''
           //             );
           //         }
           //     }
           // }
         }, */
        /*  {
            type: 'category',
            gridIndex: 2,
            data: dates,
            // boundaryGap: false,
            scale: true,
            axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            tooltip: {
              show: false,
            },
          }, */
      ],

      // Y
      yAxis: [
        {
          type: 'value',
          scale: true,
          axisLine: { lineStyle: { color: '#8392A5' } },
          splitLine: { show: false },
          max(value) {
            const a = mathService.mul(value.max, 1.01).toFixed(4);
            const b = Number(a);
            return b;
          },
          min(value) {
            const a = mathService.mul(value.min, 0.99).toFixed(4);
            const b = Number(a);
            return b;
          },
        },
        /*  {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLine: { lineStyle: { color: '#8392A5' } },
            axisLabel: {
              show: true,
              formatter: function(value, index) {
                let newValue;
                let valueString = value.toString();
                if (valueString.length >= 9) {
                  newValue = value / 100000000;
                } else if (valueString.length < 9 && valueString.length >= 5) {
                  newValue = value / 10000;
                } else {
                  newValue = value;
                }
                return newValue + 'W';
              },
            },
            /!*axisLine: {show: false},
            axisTick: {show: false},*!/
            splitLine: { show: false },
          }, */
        /* {
          scale: true,
          gridIndex: 2,
          splitNumber: 2,
          axisLine: { lineStyle: { color: '#8392A5' } },
          /!* axisLabel: {show: true, formatter:  function (value, index) {
               let newValue;
               let valueString = value.toString();
               if(valueString.length>=9){
                 newValue = value/100000000;
               }else if(valueString.length<9&&valueString.length>=5){
                 newValue = value/10000;
               }else{
                 newValue = value;
               }
               return newValue+'W';
             }},*!/
          /!*axisLine: {show: false},
          axisTick: {show: false},*!/
          splitLine: { show: false },
        }, */
      ],

      // Pointer
      axisPointer: {
        link: { xAxisIndex: 'all' },
        label: {
          backgroundColor: '#777',
        },
      },

      // v
      visualMap: {
        show: false,
        seriesIndex: 5,
        dimension: 1,
        pieces: [
          {
            value: 1,
            color: '#00da68',
          },
          {
            value: -1,
            color: '#FD1050',
          },
        ],
      },

      // S
      series: [
        {
          type: klineStyle ? 'candlestickUSA' : 'candlestick',
          name: '日K',
          data,
          // dimensions: ['date', 'open', 'close', 'highest', 'lowest'],
          markLine: {
            symbol: 'none',
            data: [],
          },
          itemStyle: {
            normal: {
              color: '#FD1050',
              color0: '#00da68',
              borderColor: '#FD1050',
              borderColor0: '#00da68',
            },
          },
        },
        {
          name: 'MA5',
          type: 'line',
          data: calculateMA(5, data),
          symbol: 'none',
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'MA10',
          type: 'line',
          symbol: 'none',
          data: calculateMA(10, data),
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'MA20',
          type: 'line',
          symbol: 'none',
          data: calculateMA(20, data),
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        {
          name: 'MA30',
          type: 'line',
          symbol: 'none',
          data: calculateMA(30, data),
          smooth: true,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 1,
            },
          },
        },
        /* {
           name: 'Volume',
           type: 'bar',
           xAxisIndex: 1,
           yAxisIndex: 1,
           data: volumes,
           itemStyle: {
             normal: {
               color: function(params) {
                 let color;
                 if (data[params.dataIndex][1] > data[params.dataIndex][0]) {
                   color = '#FD1050';
                 } else {
                   color = '#00da68';
                 }
                 return color;
               },
             },
           },
         }, */
        /*   {
             name: 'MACD',
             type: 'bar',
             xAxisIndex: 2,
             yAxisIndex: 2,
             data: data.macds,
             itemStyle: {
               normal: {
                 color: function(params) {
                   let color;
                   if (params.data >= 0) {
                     color = '#ef232a';
                   } else {
                     color = '#14b143';
                   }
                   return color;
                 },
               },
             },
           },
           {
             name: 'DIF',
             type: 'line',
             smooth: true,
             showSymbol: false,
             xAxisIndex: 2,
             yAxisIndex: 2,
             data: data.difs,
           },
           {
             name: 'DEA',
             type: 'line',
             smooth: true,
             showSymbol: false,
             xAxisIndex: 2,
             yAxisIndex: 2,
             data: data.deas,
           }, */
      ],
    };

    myChart.setOption(option, true);
  }

  onRequestData(symbol) {
    const that = this;
    // debugger
    $.ajax({
      type: 'GET',
      url: `http://fss.91stock.net/fss/Kline/RelativeStrengthKline?myStock=${symbol}`,
      contentType: 'application/x-www-form-urlencoded;charset=utf-8',
      dataType: 'json',
      async: true,
      success(data) {
        if (data.code === 1) {
          const spiltD = splitData(data.list);
          that.setOption(spiltD.times, spiltD.datas);
        }
      },
      error(e) {
        console.log(e);
        return { success: false };
      },
    });
  }

  render() {
    const { loading } = this.props;
    const { klineStyle } = this.state;
    const { dispatch, mainId } = this.props;
    return (
      <div>
        <div id={mainId} style={{ width: '100%', height: '444px' }} />
      </div>
    );
  }

  componentDidMount() {
    const that = this;
    const { dispatch, mainId, symbol } = this.props;
    const main = document.getElementById(mainId);
    myChart = echarts.init(main, '', { renderer: 'svg' });
    this.onRequestData(symbol);
    window.addEventListener('resize', () => {
      myChart.resize();
    });
  }

  componentWillUnmount() {}
}

export default KlineEchartsNewTwo;
